package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.hmdp.utils.RedisConstants.STREAM_ORDER_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private IVoucherOrderService voucherOrderService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    // TODO 使用MQ替换Redis中的基于Stream的消息队列
    private IVoucherOrderService proxy;

    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(() -> {
            while (true) {
                try {
                    // 1.获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS hmdp:stream.orders >
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(STREAM_ORDER_KEY, ReadOffset.lastConsumed())
                    );
                    // 2.判断消息获取是否成功
                    if (read == null || read.isEmpty()) {
                        // 2.1 如果为null，说明没有消息，继续下一次循环
                        continue;
                    }
                    // 3.如果获取成功，说明有消息，可以下单
                    VoucherOrder voucherOrder = BeanUtil.
                            fillBeanWithMap(read.get(0).getValue(), new VoucherOrder(), true);

                    // 处理下单业务逻辑
                    handleVoucherOrder(voucherOrder);

                    // 4.ACK确认 XACK hmdp:stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(
                            STREAM_ORDER_KEY, "g1", read.get(0).getId());


                } catch (Exception e) {
                    log.error("创建订单失败", e);
                    handlePendingList();
                }
            }
        });
    }

    private void handlePendingList() {
        while (true) {
            try {
                // 1.获取pengding-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 STREAMS hmdp:stream.orders 0
                List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(STREAM_ORDER_KEY, ReadOffset.from("0"))
                );
                // 2.判断消息获取是否成功
                if (read == null || read.isEmpty()) {
                    // 2.1 如果为null，说明pengding-list没有消息，结束循环
                    break;
                }
                // 3.如果获取成功，说明有消息，可以下单
                VoucherOrder voucherOrder = BeanUtil.
                        fillBeanWithMap(read.get(0).getValue(), new VoucherOrder(), true);

                // 处理下单业务逻辑
                handleVoucherOrder(voucherOrder);

                // 4.ACK确认 XACK hmdp:stream.orders g1 id
                stringRedisTemplate.opsForStream().acknowledge(
                        STREAM_ORDER_KEY, "g1", read.get(0).getId());
            } catch (Exception e) {
                log.error("处理pengding-list订单异常", e);
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }


    // 处理下单业务逻辑
    private void handleVoucherOrder(VoucherOrder voucherOrder) {

        // Long userId = voucherOrder.getUserId();
        // // 获取锁
        // RLock lock = redissonClient.getLock("hmdp:lock:order:" + userId);
        // /*
        //  * tryLock() 无参构造函数，默认等待时间为-1，表示不等待；默认超时时间为30秒
        //  */
        // boolean isLock = lock.tryLock();
        // if (!isLock) {
        //     log.error("不允许重复下单");
        //     return;
        // }
        // try {
        //     proxy.createVoucherOrder(voucherOrder);
        // } finally {
        //     lock.unlock();
        // }
        proxy.createVoucherOrder(voucherOrder);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 查询优惠券信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if (voucher == null) {
            return Result.fail("此优惠券不存在");
        }
        // 判断秒杀是否开始
        LocalDateTime beginTime = voucher.getBeginTime();
        if (beginTime.isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始");
        }
        // 判断秒杀是否结束
        LocalDateTime endTime = voucher.getEndTime();
        if (endTime.isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束");
        }

        // 1.执行lua脚本
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString());
        // 2.判断结果是否为0
        int r = result.intValue();
        if (r != 0) {
            // 2.1 不为0，没有购买资格
            return Result.fail(r == 1 ? "不能重复下单" : "库存不足");
        }
        // 2.2 为0，说明没有购买过，把下单信息保存到消息队列中
        //  保存到消息队列
        // 2.3 生成订单id
        long orderId = redisIdWorker.nextId("order");
        // 2.4 获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        // 使用基于Stream的消息队列来处理订单信息
        // 将下单数据保存到消息队列中
        // redis.call("sadd", 'hmdp:stream.orders', '*', 'userId', userId, 'voucherId', voucherId, 'id', id)
        Map<String, String> map = new HashMap<>();
        map.put("userId", userId.toString());
        map.put("voucherId", voucherId.toString());
        map.put("id", String.valueOf(orderId));

        stringRedisTemplate.opsForStream().add(STREAM_ORDER_KEY, map);

        // 3.返回订单id
        return Result.ok(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        // 一人一单
        Long userId = voucherOrder.getUserId();

        int count = query()
                .eq("user_id", userId)
                .eq("voucher_id", voucherOrder.getVoucherId())
                .count();
        if (count > 0) {
            // 用户已经购买过
            log.error("您已经购买过该优惠券");
        }

        // 扣减库存
        LambdaUpdateWrapper<SeckillVoucher> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                // .set(SeckillVoucher::getStock, stock - 1)
                .setSql("stock = stock - 1")
                .eq(SeckillVoucher::getVoucherId, voucherOrder.getVoucherId())
                .gt(SeckillVoucher::getStock, 0);
        boolean update = seckillVoucherService.update(updateWrapper);
        if (!update) {
            log.error("库存不足");
        }
        // 数据库创建订单
        boolean save = voucherOrderService.save(voucherOrder);
        if (!save) {
            log.error("下单失败");
        }
    }
}
